//
//  AddLadingBillThreeVC.m
//  ReceiptDelivery
//
//  Created by 吕晶 on 2020/7/6.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "AddLadingBillThreeVC.h"
#import "AddLadingBillStatusView.h"
#import "LadingRequireMainModel.h"
#import "LadingRequireCell.h"
#import "AddLadingBillSuccessVC.h"

@interface AddLadingBillThreeVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) AddLadingBillStatusView *statusView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) NSArray *shippingModeArray;//运输方式
@property (nonatomic, strong) NSArray *carRequireModeArray;//车辆要求
@property (nonatomic, strong) NSArray *jieSuanTypeArray;//结算方式

@end

@implementation AddLadingBillThreeVC

-(NSArray *)shippingModeArray {
    if (!_shippingModeArray) {
        _shippingModeArray = [NSArray array];
    }
    return _shippingModeArray;;
}

-(NSArray *)carRequireModeArray {
    if (!_carRequireModeArray) {
        _carRequireModeArray = [NSArray array];
    }
    return _carRequireModeArray;;
}

-(NSArray *)jieSuanTypeArray {
    if (!_jieSuanTypeArray) {
        _jieSuanTypeArray = [NSArray array];
    }
    return _jieSuanTypeArray;
}

-(AddLadingBillStatusView *)statusView {
    if (!_statusView) {
        _statusView = [[AddLadingBillStatusView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 75)];
        _statusView.status = 3;
    }
    return _statusView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
        
        UIButton *lastBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, (_bottomView.nim_width - 60 - 15) * 0.5, 44)];
        [lastBtn setBackgroundColor:HexColor(0xffffff)];
        lastBtn.layer.masksToBounds = YES;
        lastBtn.layer.cornerRadius = 6;
        lastBtn.layer.borderWidth = 1;
        lastBtn.layer.borderColor = HexColor(0xF2F2F5).CGColor;
        [lastBtn setTitle:@"上一步" forState:0];
        [lastBtn setTitleColor:HexColor(0x585974) forState:0];
        lastBtn.titleLabel.font = BoldFontOfSize(16);
        [lastBtn addTarget:self action:@selector(lastClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:lastBtn];
        
        UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(lastBtn.nim_right + 15, 10, (_bottomView.nim_width - 60 - 15) * 0.5, 44)];
        [nextBtn setBackgroundColor:Color_ThemeColor];
        nextBtn.layer.masksToBounds = YES;
        nextBtn.layer.cornerRadius = 6;
        [nextBtn setTitle:@"确认提交" forState:0];
        [nextBtn setTitleColor:HexColor(0xffffff) forState:0];
        nextBtn.titleLabel.font = BoldFontOfSize(16);
        [nextBtn addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:nextBtn];
    }
    return _bottomView;
}

- (void)lastClick {
    [self.rt_navigationController popViewControllerAnimated:YES];
}

- (void)nextClick {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    __block BOOL haveService = NO;
    __block int delivery = 0;
    [self.billModel.requireModel.delivery enumerateObjectsUsingBlock:^(LadingDeliveryModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            haveService = YES;
            delivery = obj.Id;
        }
    }];
    if (haveService) {
        [dic setValue:@(delivery) forKey:@"delivery"];
    }else {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择服务方式"];
        return;
    }
    
    __block BOOL haveTsTime = NO;
    __block int tsTime = 0;
    [self.billModel.requireModel.tranTime enumerateObjectsUsingBlock:^(LadingTranTimeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.isSelected) {
            haveTsTime = YES;
            tsTime = obj.Id;
        }
    }];
    if (haveTsTime) {
        [dic setValue:@(tsTime) forKey:@"tsTime"];
    }else {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择运输时效"];
        return;
    }
    
    if (self.billModel.requireModel.shippingModeId.length) {
        [dic setValue:self.billModel.requireModel.shippingModeId forKey:@"transport"];
    }else {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择运输方式"];
        return;
    }
    
    if (self.billModel.requireModel.carRequireModeId.length) {
        [dic setValue:self.billModel.requireModel.carRequireModeId forKey:@"needCar"];
    }else {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择车辆要求"];
        return;
    }
    
    if (self.billModel.requireModel.jieSuanTypeId.length) {
        [dic setValue:self.billModel.requireModel.jieSuanTypeId forKey:@"settleSty"];
    }else {
        [MBProgressHUD leShowFailedHUD:self.view message:@"请选择结算方式"];
        return;
    }
    if (self.dp_id.length) {
        [dic setValue:self.dp_id forKey:@"dp_id"];
    }else {
        if (self.billModel.supplier.t_id.length) {
            [dic setValue:self.billModel.supplier.t_id forKey:@"t_id"];
        }
    }
    
    if (self.billModel.heTong.co_id.length) {
        [dic setValue:self.billModel.heTong.co_id forKey:@"co_id"];
    }
    if (self.billModel.tiAddress.w_id.length) {
        [dic setValue:self.billModel.tiAddress.w_id forKey:@"w_id"];
    }
    if (self.billModel.shouAddress.sa_id.length) {
        [dic setValue:self.billModel.shouAddress.sa_id forKey:@"sa_id"];
    }
    if (self.billModel.beginTime.length) {
        [dic setValue:self.billModel.beginTime forKey:@"startTime"];
    }
    if (self.billModel.endTime.length) {
        [dic setValue:self.billModel.endTime forKey:@"endTime"];
    }
    if (self.billModel.requireDate.length) {
        [dic setValue:self.billModel.requireDate forKey:@"arrivalTime"];
    }
    if (self.billModel.aorder.length) {
        [dic setValue:self.billModel.aorder forKey:@"aorder"];
    }
    if (self.billModel.ynum.length) {
        [dic setValue:self.billModel.ynum forKey:@"ynum"];
    }
    if (self.billModel.requireModel.allWeight.length) {
        [dic setValue:self.billModel.requireModel.allWeight forKey:@"allWeight"];
    }
    if (self.billModel.requireModel.allVolume.length) {
        [dic setValue:self.billModel.requireModel.allVolume forKey:@"allVolume"];
    }
    if (self.billModel.requireModel.files.length) {
        [dic setValue:self.billModel.requireModel.files forKey:@"fileInfo"];
    }
    if (self.billModel.requireModel.remark.length) {
        [dic setValue:self.billModel.requireModel.remark forKey:@"remarks"];
    }
    if (self.billModel.requireModel.insuranceValue.length) {
        [dic setValue:self.billModel.requireModel.insuranceValue forKey:@"price"];
    }
    NSMutableArray *goodArr = [NSMutableArray array];
    [self.billModel.goodArray enumerateObjectsUsingBlock:^(LadingGoodMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.type == 1) {
            NSMutableDictionary *dd = [NSMutableDictionary dictionary];
            [dd setObject:obj.Id forKey:@"thg_id"];
            [dd setObject:obj.g_id forKey:@"g_id"];
            [dd setObject:@(obj.default_num) forKey:@"num"];
            [dd setObject:@(obj.default_pnum) forKey:@"pnum"];
            [goodArr addObject:dd];
        }
    }];
    if (goodArr.count) {
        [dic setObject:[FactoryMethod stringWithJSONData:goodArr] forKey:@"goodsList"];
    }
    [HttpRequest PostWithApi:self.dp_id.length ? ReceiptDeliveryEditLadingCommit : ReceiptDeliveryAddLadingCommit params:dic progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            AddLadingBillSuccessVC *vc = [AddLadingBillSuccessVC new];
            vc.dp_id = responseObject;
            [self.rt_navigationController pushViewController:vc animated:YES];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.statusView.nim_bottom, ScreenW, ScreenH - self.bottomView.nim_height - NaviHeight - self.statusView.nim_height)];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"新建提货单";
    [self mathAllWeightAndVolume];
    [self.view addSubview:self.statusView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.tableView];
    [self requestForConfig];
}

- (void)mathAllWeightAndVolume {
    if (!self.billModel.requireModel) {
        self.billModel.requireModel = [LadingRequireMainModel new];
    }
    __block CGFloat allWeight = 0;
    __block CGFloat allVolume = 0;
    [self.billModel.goodArray enumerateObjectsUsingBlock:^(LadingGoodMainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.type == 1) {
            allWeight += obj.default_num * [obj.weight floatValue];
            allVolume += obj.default_pnum * [obj.volume floatValue];
        }
    }];
    self.billModel.requireModel.allWeight = [FactoryMethod removerNumberWithZero:[NSString stringWithFormat:@"%.2f",allWeight]];
    self.billModel.requireModel.allVolume = [FactoryMethod removerNumberWithZero:[NSString stringWithFormat:@"%.2f",allVolume]];
    [self.tableView reloadData];
}

- (void)requestForConfig {
    [HttpRequest GetWithApi:ReceiptDeliveryAddLadingConfig params:@{} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.billModel.requireModel.delivery = [LadingDeliveryModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"delivery"]];
            if (self.dp_id.length) {
                [self.billModel.requireModel.delivery enumerateObjectsUsingBlock:^(LadingDeliveryModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (self.billModel.requireModel.deliveryId == obj.Id) {
                        obj.isSelected = YES;
                    }
                }];
            }
            self.billModel.requireModel.tranTime = [LadingTranTimeModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"tsTime"]];
            if (self.dp_id.length) {
                [self.billModel.requireModel.tranTime enumerateObjectsUsingBlock:^(LadingTranTimeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (self.billModel.requireModel.tsTimeId == obj.Id) {
                        obj.isSelected = YES;
                    }
                }];
            }
            self.billModel.requireModel.tipRemarkArray = [LadingRemarkModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"remarks"]];
            self.shippingModeArray = [responseObject objectForKey:@"transport_mode"];
            if (self.dp_id.length) {
                [self.shippingModeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([self.billModel.requireModel.shippingModeId isEqualToString:[NSString stringWithFormat:@"%@",[obj objectForKey:@"id"]]]) {
                        self.billModel.requireModel.shippingMode = [obj objectForKey:@"name"];
                    }
                }];
            }
            self.carRequireModeArray = [responseObject objectForKey:@"car_require"];
            if (self.dp_id.length) {
                [self.carRequireModeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([self.billModel.requireModel.carRequireModeId isEqualToString:[NSString stringWithFormat:@"%@",[obj objectForKey:@"id"]]]) {
                        self.billModel.requireModel.carRequireMode = [obj objectForKey:@"name"];
                    }
                }];
            }
            self.jieSuanTypeArray = [responseObject objectForKey:@"settleSty"];
            if (self.billModel.heTong.type.length) {
                [self.jieSuanTypeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSDictionary *dd = (NSDictionary *)obj;
                    if ([self.billModel.heTong.type isEqualToString:[NSString stringWithFormat:@"%@",dd[@"id"]]]) {
                        self.billModel.requireModel.jieSuanType = dd[@"name"];
                        self.billModel.requireModel.jieSuanTypeId = [NSString stringWithFormat:@"%@",dd[@"id"]];
                    }
                }];
            }
            if (self.dp_id.length) {
                [self.jieSuanTypeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([self.billModel.requireModel.jieSuanTypeId isEqualToString:[NSString stringWithFormat:@"%@",[obj objectForKey:@"id"]]]) {
                        self.billModel.requireModel.jieSuanType = [obj objectForKey:@"name"];
                    }
                }];
            }
            [self.tableView reloadData];
        }
    } fail:^(NSError * _Nonnull error) {
        
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LadingRequireCell *cell = [LadingRequireCell LadingRequireCellWithTableView:tableView];
    cell.model = self.billModel.requireModel;
    __weak_self;
    cell.serviceBlock = ^(int serviceId) {
        [weakself.billModel.requireModel.delivery enumerateObjectsUsingBlock:^(LadingDeliveryModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSelected = obj.Id == serviceId ? YES : NO;
        }];
        [tableView reloadData];
    };
    cell.tranTimeBlock = ^(int timeId) {
        [weakself.billModel.requireModel.tranTime enumerateObjectsUsingBlock:^(LadingTranTimeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.isSelected = obj.Id == timeId ? YES : NO;
        }];
        [tableView reloadData];
    };
    cell.shippingBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        __weak_self;
        [self.shippingModeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary *dic = (NSDictionary *)obj;
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:dic[@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                weakself.billModel.requireModel.shippingMode = dic[@"name"];
                weakself.billModel.requireModel.shippingModeId = [NSString stringWithFormat:@"%@",dic[@"id"]];
                [weakself.tableView reloadData];
            }];
            [alert addAction:action1];
        }];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:cancle];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.requireBlock = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        __weak_self;
        [self.carRequireModeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSDictionary *dic = (NSDictionary *)obj;
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:dic[@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                weakself.billModel.requireModel.carRequireMode = dic[@"name"];
                weakself.billModel.requireModel.carRequireModeId = [NSString stringWithFormat:@"%@",dic[@"id"]];
                [weakself.tableView reloadData];
            }];
            [alert addAction:action1];
        }];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:cancle];
        [weakself presentViewController:alert animated:YES completion:nil];
    };
    cell.jieSuanBlock = ^{
        if (!weakself.billModel.heTong.type.length) {
            //未选择合同时，可修改结算方式，已选择合同时，结算方式默认是合同的结算方式，不能修改
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            __weak_self;
            [self.jieSuanTypeArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSDictionary *dic = (NSDictionary *)obj;
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:dic[@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    weakself.billModel.requireModel.jieSuanType = dic[@"name"];
                    weakself.billModel.requireModel.jieSuanTypeId = [NSString stringWithFormat:@"%@",dic[@"id"]];
                    [weakself.tableView reloadData];
                }];
                [alert addAction:action1];
            }];
            UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alert addAction:cancle];
            [weakself presentViewController:alert animated:YES completion:nil];
        }
    };
    cell.insuranceBlock = ^(NSString * _Nonnull insurance) {
        weakself.billModel.requireModel.insuranceValue = insurance;
    };
    cell.fileBlock = ^(NSString * _Nonnull file) {
        weakself.billModel.requireModel.files = file;
    };
    cell.remarkBlock = ^(NSString * _Nonnull remark) {
        weakself.billModel.requireModel.remark = remark;
    };
    cell.remarkChooseBlock = ^(NSString * _Nonnull remark) {
        weakself.billModel.requireModel.remark = remark;
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    LadingRequireCell *cell = [LadingRequireCell LadingRequireCellWithTableView:tableView];
    cell.model = self.billModel.requireModel;
    return cell.height;
}

@end
